package cn.itcast.redisdemo.anno;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Aspect
@Order(0)
@Component
public class RepeatLockAspect {

    @Resource
    private RedissonClient redissonClient;

    // 定义切点
    @Pointcut("@annotation(RepeatLock)")
    public void pointCut() {
    }


    @Around(value = "pointCut() && @annotation(repeatLock)")
    public Object around(ProceedingJoinPoint joinPoint, RepeatLock repeatLock) throws Throwable {
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        String key =  className+":"+methodName;
        // 尝试获取锁
        RLock lock = redissonClient.getLock(key);
 
        boolean tryLock = lock.tryLock();
        log.info("尝试获得锁：key:{},结果：{}",key,tryLock);
        if (!tryLock) {
            throw new RuntimeException("重复请求");
        }

        Object proceed;
        try {
            // 执行方法业务逻辑
            proceed = joinPoint.proceed();
        } finally {
            // 若方法内部抛出异常保证锁能正常释放
            lock.unlock();
            log.info("释放锁");
        }
        return proceed;
    }

}

